package multiThreadSafe;

/**
 * # @File  : TickSaleOne.java
 * # @Author: Lomo
 * # @Site  : lomo.space
 * # @Date  : 2021-09-12
 * # @Desc  : 方式1：使用同步代码块方式保障多线程安全
 * 场景：多线程卖票
 */
public class TickSaleOne {
    public static void main(String[] args) {
        // 创建任务类对象
        RunnableImpl run = new RunnableImpl();
        Thread t0 = new Thread(run);
        Thread t1 = new Thread(run);
        Thread t2 = new Thread(run);

        // 调用 start 方法开启多线程任务
        t0.start();
        t1.start();
        t2.start();

    }
}

class RunnableImpl implements Runnable {
    private int ticket = 100;

    Object obj = new Object();

    // 多线程任务: 模拟多人卖票场景
    @SuppressWarnings("InfiniteLoopStatement")
    @Override
    public void run() {
        while (true) {
            synchronized (obj) {
                if (ticket > 0) {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "-- 正在售卖第 " + ticket + "张票");
                    ticket --;
                }
            }
        }
    }
}
